<script setup>
import {ElMessage, ElMessageBox, ElUpload} from 'element-plus';
import {reactive, ref} from 'vue'
import {useRouter} from "vue-router";
import {useUserStore} from "@/store";
import {savePost} from "@/api/post";
import {Plus} from "@element-plus/icons-vue";
import {SUCCESS} from "@/core/constants/HttpStatus";

const router = useRouter();
const userStore = useUserStore();
// console.log(userStore)
const {unickname} = userStore.userInfo; //用户昵称

const POST_TYPE = {
  IDEA: 0,
  TEAM: 1,
  CHAT: 3
}
// 发帖表单
const postFormData = reactive({
  title: '',
  type: POST_TYPE.IDEA,
  content: ''
})
const postFormRef = ref(null);
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 5, max: 30, message: '标题长度应满足5-30个字', trigger: 'blur' },
  ],
  content: [
    {required: true, message: '请输入正文内容'}
  ]
}
// 上传图片
const imgLimitNum = 3;
const imageFileList = ref([]);
const uploaderRef = ref(null);
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true
}
// 图片上传检测
const httpRequest = (options) => (new Promise((resolve) => {
  imageFileList.value.push(options.file);
  resolve(null);
}))
const handleBeforeUpload = (rawFile) => {
  const AllowImgTypes = ['image/jpg', 'image/jpeg', 'image/png'];
  console.log(rawFile.type);
  if (!AllowImgTypes.includes(rawFile.type)) {
    ElMessage.error('图片格式必须为 jpg/jpeg/png！')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  return true
}
const handleExceed = () => {
  ElMessage.warning(
      `仅支持上传${imgLimitNum}张图片！`
  );
};
// 移除文件之前
const handleBeforeRemove = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
      `取消上传 ${uploadFile.name} ?`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }
  ).then(
      () => true,
      () => false
  );
};
// 移除
const handleRemove = (file) => {
  // console.log(file);
  const idx = imageFileList.value.findIndex(img => img.uid === file.uid);
  console.log(idx);
  imageFileList.value.splice(idx, 1);
}
//重置
const resetPost = () => {
  postFormRef.value.resetFields();
  uploaderRef.value.clearFiles();
  imageFileList.value = [];
};
//传递发帖参数内容
const submitPost = async () => {
  const {title, content, type} = postFormData;
  const formData = new FormData();
  formData.append('unickname', unickname);
  formData.append('title', title);
  formData.append('content', content);
  formData.append('type', type);

  if (imageFileList.value.length > 0) {
    for (const image of imageFileList.value) {
      formData.append('file', image);
    }
  } else {
    formData.append('file', '');
  }

  try {
    const res = await savePost(formData);
    const {code, msg} = res.data;
    if(code != SUCCESS) {
      throw new Error(msg)
    }
    ElMessage.success("发布成功");
    resetPost();
    router.back();
  } catch (e) {
    ElMessage.error(e?.message || '发布失败');
  }
};
</script>

<template>
  <div class="post-container">
    <div class="container-top">
      <div class="go-back" @click="router.back()">
        返回
      </div>
    </div>
    <div class="container-body">
      <el-form :model="postFormData" :rules="rules" ref="postFormRef" label-position="top">
        <el-form-item prop="title">
          <el-input
              class="title-input"
              v-model="postFormData.title"
              placeholder="请输入文章标题（5-30字）"
              style="height: 40px;"
              clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="选择分区" label-position="left" prop="type">
          <el-radio-group v-model="postFormData.type">
            <el-radio :label="POST_TYPE.IDEA">创意交流</el-radio>
            <el-radio :label="POST_TYPE.TEAM">学生组队</el-radio>
            <el-radio :label="POST_TYPE.CHAT">畅聊天地</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="content">
          <el-input
              v-model="postFormData.content"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 6 }"
              placeholder="请输入正文内容"
          ></el-input>
          <div class="word-num-tip">共{{ postFormData.content?.length }}字</div>
        </el-form-item>
        <!--    自定义request，添加图片进imageFileList    -->
        <div class="img-upload-box">
          <div class="label">图片文件：<span class="tip">仅支持不超过5MB的 jpg/jpeg/png 格式的图片</span></div>
          <el-upload
              ref="uploaderRef"
              :http-request="httpRequest"
              multiple
              list-type="picture-card"
              :limit="imgLimitNum"
              :on-preview="handlePictureCardPreview"
              :on-exceed="handleExceed"
              :before-upload="handleBeforeUpload"
              :before-remove="handleBeforeRemove"
              :on-remove="handleRemove"
          >
            <el-icon class="uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </div>
        <el-row justify="end">
          <el-button type="default" @click="resetPost">重置</el-button>
          <el-button type="primary" @click="submitPost">发布</el-button>
        </el-row>
      </el-form>
    </div>
    <el-dialog v-model="dialogVisible">
      <el-image style="width:100%" fit="cover" :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<style lang="less" scoped>
body {
  background-color: #f0f8ff;
}
.post-container {
  //width: 1000px;
  background-color: #fff;
}

.container-top {
  padding-left: 30px;
  overflow: hidden;
  height: 50px;
  .go-back {
    cursor: pointer;
    color: #1e9ab5;
    line-height: 50px;
  }

  .big-title {
    text-align: center;
    color: white;
    font-weight: 800;
    font-size: x-large;
    height: 40px;
    line-height: 40px;
    letter-spacing: 15px;
  }
}

.container-body {
  padding: 40px;
  padding-top: 10px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  .img-upload-box {
    .label {
      color: rgb(64, 63, 63);
      margin-bottom: 20px;
      font-weight: 550;
    }

    .label .tip {
      color: #b7b5b5;
      font-weight: 400;
      font-size: 14px;
    }
  }
}

.container-bottom {
  height: 80px;
  display: flex;
  justify-content: space-around;
  align-items: center;

  .yes {
    width: 60px;
    font-size: medium;
    border-radius: 8px;
    background-color: white;
    border: none;
  }

  .reset {
    width: 60px;
    margin-left: 10%;
    font-size: medium;
    border-radius: 8px;
    background-color: white;
    border: none;
  }
}


</style>
